#!/usr/bin/env bash
#
# Amarok Script -- see README
#
# (c) 2007 Lukas Zapletal
#
# License: GNU General Public License V2
#

# directory with playlist backups
DIR=/tmp/amarok-$(whoami)

# minimal threshold for saving (in seconds)
MINIMAL=180

# how long to keep the backups (in days)
BACKUPS=7

# show popup message when saving (can be annoying)
POPUPSAVES=1

function popup {
	dcop amarok playlist popupMessage "$1"
	#echo $1
}

# create the directory for storing playlists
if [ ! -d $DIR ]; then
	mkdir -p $DIR || popup "Cannot create directory $DIR"
fi

# remove all old playlists (older than one week)
find $DIR/*.m3u -type f -mtime +$BACKUPS -exec rm -f {} \; >/dev/null 2>/dev/null

CHANGED=1
LAST=0 # last save time
GREET=0
MINMIN=$(expr $MINIMAL / 60)

while read NTF; do 

	CMD=${NTF%% *}
	TIME=$(date +%s)
	PERIOD=$(expr $TIME - $LAST)

    # is the user working something with the playlist?
	if [ "$CMD" = "playlistChange:" ]; then
        CHANGED=1
    fi

    # did user do something with the playlist and time threshold elapsed?
	if [ $CHANGED -eq 1 -a $PERIOD -gt $MINIMAL ]; then

		# save the playlist
		dcop amarok playlist saveM3u $DIR/playlist-$TIME.m3u false

        # and remember when we did it
        LAST=$TIME
        CHANGED=0

		# we are done; greet the user if this is first save
		if [ $GREET -eq 0 ]; then
			GREET=1
			popup "Your playlist is guarded, autosave is set to $DIR (every $MINMIN min.)"
        elif [ $POPUPSAVES -eq 1 ]; then
			popup "Your playlist has been saved."
		fi
	fi
done

# vim: set sw=4 ts=4 sts=4 sta et ai fenc=utf-8 : #

